package com.yanxin.credit.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yanxin.credit.dto.CarDTO;
import com.yanxin.credit.dto.LoginUserDTO;
import com.yanxin.credit.dto.PageDataInfo;
import com.yanxin.credit.entity.Car;
import com.yanxin.credit.mapper.CarMapper;
import com.yanxin.credit.mapstruct.CarStruct;
import com.yanxin.credit.service.ICarService;
import com.yanxin.credit.service.TokenService;
import com.yanxin.credit.utils.BeanUtils;
import com.yanxin.credit.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {

    private final CarMapper carMapper;

    private final CarStruct carStruct;

    private TokenService tokenService;

    public CarServiceImpl(CarMapper carMapper, CarStruct carStruct, TokenService tokenService) {
        this.carMapper = carMapper;
        this.carStruct = carStruct;
        this.tokenService = tokenService;
    }

    public List<Car> selectByRecycleTime(Date startTime, Date endTime) {

        QueryWrapper<Car> query = new QueryWrapper<>();
        query.ge("recycle_time", startTime).le("recycle_time", endTime);
        return carMapper.selectList(query);
    }

    @Override
    public Car insertCar(CarDTO carDto) {

        Car car = BeanUtils.copy(carDto, Car.class);
        if (ObjectUtil.isNull(car.getCarId())) {
            car.setCreateTime(new Date());
            // 回收时间
            car.setRecycleTime(new Date());
        }
        LoginUserDTO loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        car.setCreateUser(loginUser.getUser().getId());
        saveOrUpdate(car);
        return car;
    }

    @Override
    public int dropCar(long carId) {

        return carMapper.deleteById(carId);
    }

    @Override
    public PageDataInfo listBySelective(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Car> query = new QueryWrapper<>();
        query.orderByDesc("create_time");
        List<Car> cars = carMapper.selectList(query);
        return new PageDataInfo(cars);
    }

}
